package com.hd.appcommon.utils;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.dingtalkworkflow_1_0.Client;
import com.aliyun.dingtalkworkflow_1_0.models.GrantProcessInstanceForDownloadFileHeaders;
import com.aliyun.dingtalkworkflow_1_0.models.GrantProcessInstanceForDownloadFileRequest;
import com.aliyun.dingtalkworkflow_1_0.models.GrantProcessInstanceForDownloadFileResponse;
import com.aliyun.dingtalkworkflow_1_0.models.GrantProcessInstanceForDownloadFileResponseBody;
import com.aliyun.tea.TeaException;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiGettokenRequest;
import com.dingtalk.api.request.OapiV2UserGetuserinfoRequest;
import com.dingtalk.api.response.OapiGettokenResponse;
import com.dingtalk.api.response.OapiV2UserGetuserinfoResponse;
import com.hd.appcommon.constant.Constant;
import com.taobao.api.ApiException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.xml.ws.Response;
import java.util.concurrent.TimeUnit;

import static com.aliyun.teautil.Common.empty;
import static com.hd.appcommon.constant.URLConstant.URL_GET_TOKKEN;

/**
 * 钉钉请求工具类
 */
@Slf4j
@Component
public class DDUtils {
    @Autowired
    RedisTemplate redisTemplate;


    private static String APP_KEY = "dingocqunsfqrqksqz3o";
    private static String APP_SECRET = "yz8xp39r_HFPMwdKdoX6E2HvW6WMWLZpd0a0XoyOHWm_kZObwdri0uK7XjtWowZq";

    public String getAccessToken() throws RuntimeException {


        String access_token = (String) redisTemplate.opsForValue().get("dd_access_token");
        if (access_token != null){
            System.out.println(access_token);
            return access_token;
        }

        try {
            DefaultDingTalkClient client = new DefaultDingTalkClient(URL_GET_TOKKEN);
            OapiGettokenRequest request = new OapiGettokenRequest();

            request.setAppkey(APP_KEY);
            request.setAppsecret(APP_SECRET);
            request.setHttpMethod("GET");
            OapiGettokenResponse response = client.execute(request);
            System.out.println(response.getBody());
            String accessToken = response.getAccessToken();
            redisTemplate.opsForValue().set("dd_access_token",accessToken,3600,TimeUnit.SECONDS);
            return accessToken;
        } catch (ApiException e) {
            log.error("getAccessToken failed", e);
            throw new RuntimeException();
        }
    }

    /**
     * 根据钉钉免登授权码，获取用户的信息
     * @param authCode
     * @return
     * @throws ApiException
     */
    public JSONObject getUserMsg(String authCode) {
        try{
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/getuserinfo");
            OapiV2UserGetuserinfoRequest req = new OapiV2UserGetuserinfoRequest();
            req.setCode(authCode);
            OapiV2UserGetuserinfoResponse rsp = client.execute(req, getAccessToken());
            if (rsp.isSuccess()){
                JSONObject body = JSON.parseObject(rsp.getBody());
                return body.getJSONObject("result");
            }

            return null;
        }catch (Exception e){
            log.error(e.getMessage());
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 使用 Token 初始化账号Client
     * @return Client
     * @throws Exception
     */
    public static Client createClient() throws Exception {
        Config config = new Config();
        config.protocol = "https";
        config.regionId = "central";
        return new Client(config);
    }

    public String getPicture(String processInstanceId, String fileId) throws Exception {
        System.out.println("processInstanceId: "+processInstanceId);
        System.out.println("fileId: "+fileId);
        Client client = createClient();
        GrantProcessInstanceForDownloadFileHeaders grantProcessInstanceForDownloadFileHeaders = new GrantProcessInstanceForDownloadFileHeaders();
        grantProcessInstanceForDownloadFileHeaders.xAcsDingtalkAccessToken = getAccessToken();
        GrantProcessInstanceForDownloadFileRequest grantProcessInstanceForDownloadFileRequest = new GrantProcessInstanceForDownloadFileRequest()
                .setProcessInstanceId(processInstanceId)
                .setFileId(fileId);
        GrantProcessInstanceForDownloadFileResponse rsp = client.grantProcessInstanceForDownloadFileWithOptions(grantProcessInstanceForDownloadFileRequest, grantProcessInstanceForDownloadFileHeaders, new RuntimeOptions());
        GrantProcessInstanceForDownloadFileResponseBody body = rsp.getBody();
        GrantProcessInstanceForDownloadFileResponseBody.GrantProcessInstanceForDownloadFileResponseBodyResult result = body.getResult();
        String url = result.getDownloadUri();
        System.out.println(url);
        return url;
    }

}
